package com.huluobo.user.view

import android.text.TextUtils
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.RoutePath
import com.huluobo.lib_base.UIState
import com.huluobo.lib_base.entity.User
import com.huluobo.lib_http.Const
import com.huluobo.user.UserIntent
import com.huluobo.user.UserViewModel
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

/**
 *  Created by LC on 2025/4/1.
 */

@Composable
fun LoginPage(navHostController: NavHostController, vm: UserViewModel = hiltViewModel()) {
    var username by remember {
        mutableStateOf("")
    }

    var password by remember {
        mutableStateOf("")
    }

    var role by remember {
        mutableStateOf("员工")
    }
    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        Log.e("TagA", "登录失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        EMClient.getInstance().login(username, password, object : EMCallBack {
                            override fun onSuccess() {
                                ToastUtils.showLong("登录成功")
                                val mmkv = MMKV.defaultMMKV()
                                mmkv.encode(Const.PARAM_USERNAME, username)
                                mmkv.encode(Const.PARAM_ROLE, role)
                                mmkv.encode(Const.PARAM_TOKEN, it.data.toString())
                                runBlocking(Dispatchers.Main) {
                                    navHostController.popBackStack()
                                }
                            }

                            override fun onError(code: Int, error: String?) {
                                ToastUtils.showLong("登陆失败:$error,code:$code")
                            }
                        })
                    }
                }
            }
        }
    })

    Column(verticalArrangement = Arrangement.spacedBy(20.dp), modifier = Modifier.padding(20.dp)) {
        BaseTitle(title = "登录", navHostController = navHostController)
        Spacer(modifier = Modifier.height(100.dp))
        OutlinedTextField(value = username, onValueChange = { username = it }, Modifier.fillMaxWidth(), label = {
            Text(text = "用户名")
        }, leadingIcon = { Icon(imageVector = Icons.Default.AccountCircle, contentDescription = "") })
        OutlinedTextField(value = password, onValueChange = { password = it }, Modifier.fillMaxWidth(), label = {
            Text(text = "密码")
        }, visualTransformation = PasswordVisualTransformation(),
            leadingIcon = { Icon(imageVector = Icons.Default.Lock, contentDescription = "") })
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text(text = "角色 : ")
            Checkbox(checked = role == "经理", onCheckedChange = {
                if (it) {
                    role = "经理"
                }
            })
            Text(text = "经理")
            Checkbox(checked = role == "员工", onCheckedChange = {
                if (it) {
                    role = "员工"
                }
            })
            Text(text = "员工")
        }

        Text(text = "用户注册", modifier = Modifier.clickable {
            navHostController.navigate(RoutePath.ADD_EMPLOYEE)
        })

        Button(onClick = {
            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                ToastUtils.showLong("输入项不能为空")
                return@Button
            }

            if (!username.matches(Regex("[A-z0-9]{2,10}"))) {
                ToastUtils.showLong("用户名需要字母或者数字,2到10位")
                return@Button
            }

            val map = mapOf(
                Const.PARAM_U_NAME to username,
                Const.PARAM_U_PASS to password
            )

            vm.sendIntent(
//                UserIntent.Login(username, password, if (role == "经理") 1 else 2)
                UserIntent.LoginNetwork(map)
            )

        }) {
            Text(text = "登录")
        }
    }
}